package 备战春招12月27日开始刷题.力扣题目;

import java.util.Stack;
// https://leetcode-cn.com/problems/remove-k-digits/
public class lc402移掉K位数字1227 {
    public String removeKdigits(String num,int k){
        Stack<Integer> stack = new Stack<>();
        for(int i = 0;i < num.length();i++){
            int digit = num.charAt(i) -'0';
            while (k > 0 && !stack.isEmpty() && digit < stack.peek()){
                stack.pop();
                k--;
            }
            stack.push(digit);
        }
        while (k > 0 && !stack.isEmpty()){
            stack.pop();
            k--;
        }
        StringBuffer res = new StringBuffer();
        while (!stack.isEmpty()){
            res.append(stack.pop());
        }
        //trim leading zero
        while (res.length() > 0 && res.charAt(res.length()-1) == '0'){
            res.deleteCharAt(res.length()-1);
        }
        return res.length() == 0 ? "0" : res.reverse().toString();
    }

    public static void main(String[] args) {
        System.out.println(new lc402移掉K位数字1227().removeKdigits("1432219", 3));
    }
}
